package cn.sdormitory.component.bindValue.bean.info;

import cn.hutool.core.convert.Convert;
import cn.sdormitory.common.utils.StringUtils;
import cn.sdormitory.component.bindValue.annotation.BindStoreValue;
import lombok.Getter;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

public class BindStoreInfo {
    private Field rowKeyPrefixField;
    private String rowKeyPrefixDelimiter;
    private Field rowKeyValueField;
    @Getter
    private String columnKey;
    private Field columnField;

    public static BindStoreInfo generate(BindStoreValue bindStoreValue, Field prefixField,
                                         Field variableField, Field propertyField){
        BindStoreInfo info = new BindStoreInfo();
        info.rowKeyPrefixField = prefixField;
        info.rowKeyPrefixDelimiter = bindStoreValue.prefixDelimiter();
        info.rowKeyValueField = variableField;
        info.columnField = propertyField;
        info.columnKey = StringUtils.isBlank(bindStoreValue.property()) ? propertyField.getName() : bindStoreValue.property();
        return info;
    }

    public String getRowKey(Object info){
        String rowKeyPrefix = rowKeyPrefixField == null
                ? ""
                : Convert.toStr(ReflectionUtils.getField(rowKeyPrefixField, info),"");
        String rowKeyValue = Convert.toStr(ReflectionUtils.getField(rowKeyValueField, info));
        return StringUtils.isNotEmpty(rowKeyPrefix)
                ? rowKeyPrefix + rowKeyPrefixDelimiter + rowKeyValue
                : rowKeyValue;
    }

    public void setItemValue(Object item, Object value) {
        if(value == null){
            return;
        }
        Object realValue = Convert.convert(columnField.getType(), value);
        ReflectionUtils.setField(columnField, item, realValue);
    }
}
